package pong.ui.window;

import java.awt.BorderLayout;
import java.io.FileNotFoundException;
import java.io.IOException;

import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;

import pong.business.properties.PropertiesAccessor;
import pong.ui.text.GameMessage;
import pong.ui.text.GameMessageKeys;

@SuppressWarnings("serial")
public class MainWindow extends JFrame {

	private static MainWindow instance;
	
	private static final int DEFAULT_WINDOW_WIDTH = 800;
	
	private static final int DEFAULT_WINDOW_HEIGHT = 600;

	private final GamePanel gamePanel = GamePanel.getInstance();
	
	public static MainWindow getInstance() {
		if(instance == null) {
			instance = new MainWindow();
		}
		return instance;
	}
	
	private MainWindow() {
		super(GameMessage.getMessage(GameMessageKeys.MAIN_WINDOW_TITLE));
		
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setLayout(new BorderLayout());
		
		float sizeCoefficient;
		try {
			sizeCoefficient = PropertiesAccessor.getInstance().getSizeCoefficient();
			setSize((int)(sizeCoefficient * DEFAULT_WINDOW_WIDTH), 
					(int)(sizeCoefficient * DEFAULT_WINDOW_HEIGHT));
			
		} catch (FileNotFoundException exception) {
			displayErrorMessage(GameMessage.getMessage(GameMessageKeys.CONFIGURATION_FILE_NOT_FOUND_ERROR));
		} catch (IOException exception) {
			displayErrorMessage(GameMessage.getMessage(GameMessageKeys.CONFIGURATION_FILE_IO_ERROR));
		}

		add(gamePanel);
		
		setJMenuBar(buildMenuBar());
		
		setVisible(true);
	}
	
	private JMenuBar buildMenuBar() {
		
		JMenuBar menuBar = new JMenuBar();
		
		JMenu fileMenu = new JMenu(GameMessage.getMessage(GameMessageKeys.MENUBAR_FILE));
		JMenu helpMenu = new JMenu(GameMessage.getMessage(GameMessageKeys.MENUBAR_HELP));
		
		JMenuItem startNewGameMenuItem = new JMenuItem(GameMessage.getMessage(GameMessageKeys.MENUBARITEM_STARTGAME));
		JMenuItem exitMenuItem = new JMenuItem(GameMessage.getMessage(GameMessageKeys.MENUBARITEM_EXITGAME));
		JMenuItem aboutMenuItem = new JMenuItem(GameMessage.getMessage(GameMessageKeys.MENUBARITEM_ABOUT));
		
		fileMenu.add(startNewGameMenuItem);
		fileMenu.addSeparator();
		fileMenu.add(exitMenuItem);
		
		helpMenu.add(aboutMenuItem);

		menuBar.add(fileMenu);
		menuBar.add(helpMenu);
		
		return menuBar;
	}
	
	private void displayErrorMessage(String message) {
		JOptionPane.showMessageDialog(null, message, 
				GameMessage.getMessage(GameMessageKeys.DIALOG_ERROR_TITLE), JOptionPane.ERROR_MESSAGE);
	}
}
